package gtfaces;

import org.jsoup.nodes.*;
import org.jsoup.select.*;

import java.util.*;

import org.jsoup.Connection.Method;

import com.sun.org.apache.xml.internal.resolver.helpers.Debug;

public class TSquareClassExplorer extends Thread {

	public static Collection<TSquareClassExplorer> allTSquareClasses;
	public static String serverApiUrl;
	
	static {
		allTSquareClasses = new HashSet<TSquareClassExplorer>();
		serverApiUrl = "http://m2.cip.gatech.edu/developer/droptables/widget/facesBD/content/api/GtFacesAPI";
	}
	
	private String link;
	private FacesHandler facesHandler;
	private RunResults rResults;
	
	public String getLink() {
		return link;
	}
	
	public void getLink(String newLink) {
		this.link = newLink;
	}
	
	public TSquareClassExplorer(String className, String link, FacesHandler facesHandler, RunResults rResults) {
		super(className);
		this.link = link;
		this.facesHandler = facesHandler;
		this.rResults = rResults;
		// Add to the static collection
		allTSquareClasses.add(this);
	}
	
	private Document getDocument(String url, Map<String, String> data) {
		return getDocument(url, data, Method.GET);
	}
	
	private Document getDocument(String url, Map<String, String> data, Method meth) {
		Document doc = null;
		synchronized (facesHandler) {
			try {
				doc = facesHandler.send(url, null, Method.GET, false);				
			} catch (Exception e) {
				e.printStackTrace();
				System.err.println(getName() + " did not import roster successfully."); // TODO
			}
		}
		return doc;
	}
	
	@Override
	public void run() {
		if (link != null) {
			// Get Course page
			Document doc = getDocument(link, null);
			Elements eles = doc.select("a:contains(Roster)");
			if (eles.size() == 1) {
				// Get Roster page
				doc = getDocument(eles.get(0).attr("href"), null);
				eles = doc.select("iframe[title*=Roster]");
				if (eles.size() == 1) {
					// Get Roster Picture iFrame
					String picUrl = eles.get(0).attr("src").replaceAll("\\?panel=Main", "/pictures");
					doc = getDocument(picUrl, null);
					eles = doc.select("img");
					// Images
					int successful = handleImgElements(eles, picUrl);
					rResults.addClassResults(getName(), eles.size(), successful);
				} else
					System.err.println(getName() + " does not have pictures available for the roster."); // TODO
			} else
				System.err.println(getName() + " does not have an available class Roster."); // TODO
		}
	}
	
	private int handleImgElements(Elements eles, String url) {
		url = url.replace("pictures", "");
		int successful = 0;
		facesHandler.addWork(eles.size());
		if (FacesHandler.DEBUG)
			System.out.println("Adding work: " + eles.size());
		for (Element ele : eles) {
			if (!ele.attr("title").contains("No picture is available") && 
					ele.attr("src").contains("=")) {
				TSquareImage img = handleStudent(ele, url);
				if (img != null) {
					successful++;
					rResults.addSuccess(getName(), img);
				} else {
					rResults.addFailure(getName(), img);
				}
			}
			facesHandler.finishedWorkUnit();
		}
		return successful;
	}
	
	private TSquareImage handleStudent(Element ele, String url) {
		if (ele.attr("src").contains("pictureUnavailable.jpg") || 
				ele.attr("title").contains("No picture is available") ||
				!ele.attr("src").contains("="))
			return null;
		String studentName = ele.attr("title").replaceAll("Photo of ", "");
		String imgUrl = url + ele.attr("src");
		TSquareImage img = new TSquareImage(imgUrl, studentName, getName(), facesHandler.getName());
		try {
			String postUrl = serverApiUrl;
			facesHandler.send(postUrl, img.getData(), Method.POST, false);
		} catch (Exception e) {
			System.err.println("Failed to post information to  GTmob servers.\n\t" + e.getMessage()); // TODO
		}
		return img;	
	}
	
	@Override
	public String toString() {
		return this.getName();
	}
	
	public String getSuccessString() {
		return rResults.getSuccessString(getName());
	}
}
